from machine import Pin, I2C
from lib import *
import _thread
import time
'''
i2c = I2C(scl=Pin(16), sda=Pin(17), freq=10000000)
display = sh1106.SH1106_I2C(128, 64, i2c, None, 0x3c)
display.invert(False)
display.rotate(True)
'''
def wifi():
    ssid_list = []
    ico(display, computer, 0, 108)
    fill(display, 0, 110, 10, 10, fill=0)
    ico(display, wifi_off, 0, 118)
    display.show()
    if not wlan.isconnected():
        while True:
            rs = wlan.scan()
            for w in rs:ssid_list.append(w[0])
            for si in sipd:
                if si.encode() in ssid_list:
                    start_time = time.time()
                    wlan.connect(si, sipd[si])
                    while not wlan.isconnected():
                        if time.time()-start_time > 15:break
                else:continue
            if wlan.isconnected():break
    try:
        ntptime.settime()
        fill(display, 0, 110, 10, 10, fill=0)
        ico(display, wifi_on, 0, 118)
        display.show()
    except:
        pass


def clock():
    ti = ['','','','']
    lafod = ''
    while True:
        hour = str(time.localtime()[3])
        if len(hour) == 1:hour='0'+hour
        minute = str(time.localtime()[4])
        if len(minute) == 1:minute='0'+minute
        if ti[0] != hour[0]:
            ti[0] = hour[0]
            fill(display, 8, 8, 25, 50, fill=0)
            fontnumber(display, int(hour[0]), 8, 8, fill=1)
        if ti[1] != hour[1]:
            ti[1] = hour[1]
            fill(display, 33, 8, 25, 50, fill=0)
            fontnumber(display, int(hour[1]), 33, 8, fill=1)
        if ti[2] != minute[0]:
            ti[2] = minute[0]
            fill(display, 68, 8, 25, 50, fill=0)
            fontnumber(display, int(minute[0]), 68, 8, fill=1)
        if ti[3] != minute[1]:
            ti[3] = minute[1]
            fill(display, 93, 8, 25, 50, fill=0)
            fontnumber(display, int(minute[1]), 93, 8, fill=1)
        feng(display, 50, 8, fill=1)
        fod = '{mon}.{day}'.format(mon=time.localtime()[1],day=time.localtime()[2])
        if fod != lafod:
            fill(display, 0, 0, len(lafod)*5, 10, fill=0)
            icodate(display, fod, 0, 0, fill=1)
        display.show()
        lafod = fod

_thread.start_new_thread(clock, ())
_thread.start_new_thread(wifi, ())